package com.xiaoshuidi.cloud.module.iot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.WaterMeterCommonResponseModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.callback.EmecoDeviceCallbackReqVO;
import com.xiaoshuidi.cloud.module.iot.dal.model.watermeter.WaterMeterCommonRequestModel;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.service.EmecoCallBackService;
import com.xiaoshuidi.cloud.module.iot.service.WaterMeterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class EmecoCallBackServiceImpl implements EmecoCallBackService {

    private final static Logger LOGGER = LoggerFactory.getLogger(EmecoCallBackService.class);

    @Autowired
    DeviceRepository deviceRepository;

    @Autowired
    private WaterMeterService waterMeterService;

    @Autowired
    private DeviceRepository waterMeterDataAccess;

    @Override
    public void callback(EmecoDeviceCallbackReqVO emecoDeviceCallbackReqVO) {
        Boolean success = emecoDeviceCallbackReqVO.getSuccess();
        if (Objects.nonNull(success)&&success){
            EmecoDeviceCallbackReqVO.Data data = emecoDeviceCallbackReqVO.getData();
            if (data != null) {
                String sn = data.getSn();
                if(StrUtil.isNotBlank(sn)){
                    //根据第三方设备编号查询数据并更新
                    TbDeviceDo tbDeviceDo = deviceRepository.getDeviceByDeviceThirdNo(sn);
                    if (tbDeviceDo != null) {
                        WaterMeterCommonRequestModel waterMeterCommonRequestModel=new WaterMeterCommonRequestModel();
                        waterMeterCommonRequestModel.setDeviceNo(tbDeviceDo.getDeviceNo());
                        WaterMeterCommonResponseModel resultModel = this.waterMeterDataAccess.getWatermeterInfoBydeviceNo(waterMeterCommonRequestModel);
                        if (success) {
                            String brandNo = resultModel.getBrandNo();
                            resultModel.setCurrentReading(data.getData().doubleValue());
                            resultModel.setReportTime(new Date());
                            if (null != waterMeterCommonRequestModel.getRoomId()) {
                                resultModel.setRoomId(waterMeterCommonRequestModel.getRoomId());
                            }
                            //新增读数记录,并更新数据处理
                            waterMeterService.disposeDeviceDosage(resultModel, waterMeterCommonRequestModel.isCharging());
                        }
                    }
                }
            }
        }

    }
}
